﻿#include <iostream>
#include<csignal>
#include<thread>
#include"RedisMgr.h"
#include<mutex>
#include"MySqlMgr.h"
#include"LogicSystem.h"
#include"Cserver.h"
#include"ConfigMgr.h"
#include"AsioIOServicePool.h"
#include"ChatServiceImpl.h"
#pragma execution_character_set("utf-8")  

bool bstop = false;
std::condition_variable cond_quit;
std::mutex mutex_quit;

void text() {
	bool b = MySqlMgr::GetInstance()->text();
	return;
}

int main()
{
	auto& cfg = ConFigMgr::Inst();
	auto server_name = cfg["SelfServer"]["Name"];

	//定义一个GrpcServer

	std::string server_address(cfg["SelfServer"]["Host"] + ":" + cfg["SelfServer"]["RpcPort"]);
	ChatServiceImpl service;
	grpc::ServerBuilder builder;
	// 监听端口和添加服务
	builder.AddListeningPort(server_address, grpc::InsecureServerCredentials());
	builder.RegisterService(&service);
	// 构建并启动gRPC服务器
	std::unique_ptr<grpc::Server> server(builder.BuildAndStart());
	std::cout << "RPC Server listening on " << server_address << std::endl;

	std::cout << server_address << std::endl;

	//单独启动一个线程处理grpc服务
	std::thread  grpc_server_thread([&server]() {
		server->Wait();
		});

	try
	{
		auto pool = AsioIOServicePool::GetInstance();
		//将登录数设置为0
		RedisMgr::GetInstance()->HSet(LOGIN_COUNT, server_name, "0");


		auto cfg = ConFigMgr::Inst();
		auto pool_ = AsioIOServicePool::GetInstance();
		boost::asio::io_context io_context;
		boost::asio::signal_set signals(io_context, SIGINT, SIGTERM); //设置监听的信号
		signals.async_wait([&io_context,pool,&server](auto,auto) {
			io_context.stop();
			pool->Stop();
			server->Shutdown();
			});

		auto port_cfg = cfg["SelfServer"]["Port"];
		int port_ = static_cast<int>(std::stoi(port_cfg.c_str()));
		std::cout << port_ << std::endl;
		CServer s(io_context, port_);
		io_context.run();

		RedisMgr::GetInstance()->HDel(LOGIN_COUNT, server_name);
		RedisMgr::GetInstance()->Close();
		grpc_server_thread.join();

	}
	catch (const std::exception& e)
	{
		std::cerr << "Exception: " << e.what() << endl;
		RedisMgr::GetInstance()->HDel(LOGIN_COUNT, server_name);
		RedisMgr::GetInstance()->Close();
	}
}

